package eiisan.util.common;

import lombok.experimental.UtilityClass;
import org.springframework.data.domain.Pageable;
import org.springframework.util.Assert;

import java.util.stream.Stream;

@UtilityClass
public class StreamUtil {

    /**
     * 对stream进行分页查询
     */
    public static <T> Stream<T> startPage(Stream<T> stream, Pageable page) {
        Assert.notNull(page, "page must not be null");
        Assert.notNull(stream, "stream must not be null");
        return startPage(stream, page.getPageNumber(), page.getPageSize());
    }

    /**
     * 对stream进行分页查询
     *
     * @param pageNum  页码数。为了和mysql分页查询保持一致,小于等于1时,忽略该参数。
     * @param pageSize 单页容量
     */
    public static <T> Stream<T> startPage(Stream<T> stream, int pageNum, int pageSize) {
        Assert.notNull(stream, "stream must not be null");
        Assert.state(pageNum >= 0, "pageNum can't be negetive");
        Assert.state(pageSize > 0, "pageSize must be positive");
        return pageNum > 0 ? startRowBounds(stream, pageNum * pageSize, pageSize) : stream.limit(pageSize);
    }

    /**
     * 对stream进行分页查询
     *
     * @param limit  mysql风格的limit 0~N
     * @param offset mysql风格的offset 等于pageSize
     */
    public static <T> Stream<T> startRowBounds(Stream<T> stream, int limit, int offset) {
        Assert.notNull(stream, "stream must not be null");
        Assert.state(limit >= 0, "limit can't be negetive");
        Assert.state(offset > 0, "offset must be positive");
        return limit > 0 ? stream.skip(limit).limit(limit + offset) : stream.limit(offset);
    }

}
